package com.gimhon.login.web.controller;


import com.gimhon.login.constant.ResultCode;
import com.gimhon.login.entity.Response;
import com.gimhon.login.entity.User;
import com.gimhon.login.service.api.UserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("/register")
    public Response addUser(User user) {
        User userInfo = userService.addUser(user);
        if (userInfo == null) {
            return Response.error(ResultCode.REGISTER_FAIL);
        } else {
            userInfo.setPassword("");
            return Response.success(userInfo);
        }
    }


    @PostMapping("/login")
    public Response login(@Validated @RequestBody User user, HttpServletRequest request) {
        User userInfo = userService.login(user);
        if (userInfo == null) {
            return Response.error(ResultCode.LOGIN_FAIL);
        } else {
            request.getSession().setAttribute("user", userInfo);
            userInfo.setPassword("");
            return Response.success(userInfo);
        }
    }


    @PostMapping("/findAll")
    public List<User> getUserList() {
        return userService.getUserList();
    }
}
